<template>
  <div>
    <div style="float: left; margin-left: 20px">
      <el-input
        style="width: 200px"
        size="small"
        placeholder="请输入专业名称"
        v-model="filterText"
      >
      </el-input>
      <el-tree
        style="margin-top: 5px"
        :data="colleges"
        :props="defaultProps"
        ref="tree"
        default-expand-all
        :expand-on-click-node="false"
        node-key="id"
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
      ></el-tree>
    </div>
    <el-input
      style="width: 207px; margin-bottom: 10px; margin-left: 10px"
      size="small"
      placeholder="请输入学号"
      v-model="username"
    >
    </el-input>
    <el-input
      style="width: 207px; margin-bottom: 10px; margin-left: 10px"
      size="small"
      placeholder="请输入姓名"
      v-model="name"
    >
    </el-input>
    <el-input
      style="width: 207px; margin-bottom: 10px; margin-left: 10px"
      size="small"
      placeholder="请输入手机号"
      v-model="mobile"
    >
    </el-input>
    <el-input
      style="width: 207px; margin-bottom: 10px; margin-left: 10px"
      size="small"
      placeholder="请输入邮箱"
      v-model="email"
    >
    </el-input>
    <el-select
      v-model="enabled"
      style="width: 207px; float: left; margin-left: 20px"
      size="small"
      clearable
      placeholder="请选择学生状态"
    >
      <el-option
        v-for="item in options"
        :key="item[0]"
        :label="item[0]"
        :value="item[1]"
      >
      </el-option>
    </el-select>
    <div style="float: right">
      <div>
        <el-button
          style="float: left; margin-bottom: 12px"
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="initStudent"
          >搜索</el-button
        >
        <el-button
          style="float: left"
          icon="el-icon-refresh"
          size="small"
          @click="clearInput"
          >重置</el-button
        >
        <el-button
          style="float: left"
          type="danger"
          plain
          icon="el-icon-delete"
          size="small"
          @click="delAll"
          :disabled="this.multipleSelection.length == 0"
          >批量删除</el-button
        >
        <el-button
          style="float: left"
          icon="el-icon-plus"
          plain
          type="primary"
          size="small"
          @click="show"
          >新增</el-button
        >
        <el-upload
          style="float: left; margin-left: 10px"
          action="/student/import"
          :headers="headers"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <el-button type="info" plain size="small" icon="el-icon-download"
            >导入</el-button
          >
        </el-upload>
        <el-button
          type="warning"
          plain
          size="small"
          icon="el-icon-upload2"
          style="float: left; margin-left: 10px"
          @click="exportStuInfo"
          >导出</el-button
        >
      </div>
      <el-table
        :data="tableData"
        :cell-style="rowClass"
        :header-cell-style="headClass"
        @selection-change="handleSelectionChange"
        ><el-table-column type="selection" width="45"> </el-table-column>
        <el-table-column
          prop="username"
          label="学号"
          width="100"
        ></el-table-column>
        <el-table-column prop="name" label="姓名" width="100"></el-table-column>
        <el-table-column
          prop="college.name"
          label="专业"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="200"
        ></el-table-column>
        <el-table-column
          prop="mobile"
          label="手机号"
          width="110"
        ></el-table-column>
        <el-table-column prop="enabled" label="是否启用" width="80">
          <template slot-scope="scope">
            <el-switch
              v-if="scope.row.enabled"
              v-model="scope.row.enabled"
              @change="changeEnabled(scope.row.id, scope.row.name)"
            ></el-switch>
            <el-switch
              v-else
              v-model="scope.row.enabled"
              @change="changeDisable(scope.row.id)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          width="200"
          label="创建时间"
          align="center"
          prop="createTime"
        >
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="145"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 10px; float: right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        :current-page="currentPage"
        :page-sizes="[5, 8]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog
      title="新增学生"
      :visible.sync="dialogVisible"
      width="400px"
      center
    >
      <el-form
        :model="formData"
        ref="addForm"
        label-width="80px"
        :rules="rules"
      >
        <el-form-item prop="uid" label="专业" size="mini">
          <treeselect
            v-model="formData.uid"
            :options="parentData"
            :normalizer="normalizer"
            placeholder="选择专业"
          />
        </el-form-item>
        <el-form-item prop="username" label="学号" size="small">
          <el-input
            v-model="formData.username"
            placeholder="请输入学号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="name" label="姓名" size="small">
          <el-input v-model="formData.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码" size="small">
          <el-input
            type="password"
            v-model="formData.password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="电话号" size="small">
          <el-input
            v-model="formData.mobile"
            placeholder="请输入电话号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱" size="small">
          <el-input
            v-model="formData.email"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button size="mini" @click="dialogVisible = false">取消</el-button>
        <el-button size="mini" type="primary" @click="addStudent"
          >确定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="编辑学生"
      :visible.sync="editDialogVisible"
      width="400px"
      center
    >
      <el-form
        :model="editData"
        ref="editForm"
        label-width="80px"
        :rules="rules"
      >
        <el-form-item prop="uid" label="专业" size="mini">
          <treeselect
            v-model="editData.uid"
            :options="parentData"
            :normalizer="normalizer"
            placeholder="选择专业"
          />
        </el-form-item>
        <el-form-item prop="name" label="姓名" size="small">
          <el-input v-model="editData.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码" size="small">
          <el-input
            type="password"
            v-model="editData.password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="电话号" size="small">
          <el-input
            v-model="editData.mobile"
            placeholder="请输入电话号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱" size="small">
          <el-input
            v-model="editData.email"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button size="mini" @click="editDialogVisible = false"
          >取消</el-button
        >
        <el-button size="mini" type="primary" @click="updateStudent"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  components: { Treeselect },
  data() {
    return {
      filterText: "",
      defaultProps: {
        children: "children",
        label: "name",
      },
      colleges: [],
      editDialogVisible: false,
      multipleSelection: [],
      dialogVisible: false,
      username: "",
      name: "",
      mobile: "",
      enabled: "",
      uid: "",
      options: [
        ["启用", true],
        ["禁用", false],
      ],
      email: "",
      tableData: [],
      editData: {
        id: null,
        name: "",
        password: "",
        mobile: "",
        email: "",
        uid: null,
      },
      formData: {
        username: "",
        name: "",
        password: "",
        mobile: "",
        email: "",
        uid: null,
      },
      total: 0,
      currentPage: 1,
      pageSize: 5,
      parentData: [],
      rules: {
        username: [{ required: true, message: "请输入学号", trigger: "blur" }],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        uid: [{ required: true, message: "请选择专业", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        mobile: [{ required: true, message: "请输入手机", trigger: "blur" }],
      },
    };
  },
  computed: {
    headers() {
      return { Authorization: sessionStorage.getItem("tokenStr") };
    },
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.initCollege();
    this.initStudent();
  },
  methods: {
    //转换学院数据格式
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    show() {
      this.formData = {};
      this.dialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm('此操作将删除"' + row.name + '", 是否继续?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$delete("student/?ids=" + row.id).then((res) => {
          if (res.code == 200) {
            this.initStudent();
          }
        });
      });
    },
    delAll() {
      this.$confirm(
        '此操作将删除"' + this.multipleSelection.length + '"个学生, 是否继续?',
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        let ids = "?";
        this.multipleSelection.forEach((item) => {
          ids += "ids=" + item.id + "&";
        });
        this.$delete("student/" + ids).then((res) => {
          if (res.code == 200) {
            this.initStudent();
          }
        });
      });
    },
    updateStudent() {
      this.$refs["editForm"].validate((valid) => {
        if (valid) {
          this.$post("student/", this.editData).then((res) => {
            if (res.code == 200) {
              this.initStudent();
              this.editDialogVisible = false;
            }
          });
        } else {
          this.$message.error("数据校验失败，请检查");
        }
      });
    },
    addStudent() {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          this.$post("student/", this.formData).then((res) => {
            if (res.code == 200) {
              this.initStudent();
              this.dialogVisible = false;
            }
          });
        } else {
          this.$message.error("数据校验失败，请检查");
        }
      });
    },
    exportStuInfo() {
      this.$downloadReq("/student/export");
    },
    handleUpdate(row) {
      this.editData = {
        id: row.id,
        name: row.name,
        mobile: row.mobile,
        email: row.email,
        password: row.password,
        uid: row.college.id,
      };
      this.editDialogVisible = true;
    },
    changeEnabled(id, name) {
      this.$confirm("确定要" + '"停用"' + '"' + name + '"吗？', "系统提示", {
        confirmButtonText: "确定·",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$post("student/", { id: id, enabled: false }).then((res) => {
            if (res.code == 200) {
              this.initStudent();
            }
          });
        })
        .catch(() => {
          this.initStudent();
        });
    },
    changeDisable(id) {
      this.$post("student/", { id: id, enabled: true }).then((res) => {
        if (res.code == 200) {
          this.initStudent();
        }
      });
    },
    clearInput() {
      location.reload();
    },
    beforeAvatarUpload(file) {
      var testMsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (testMsg != "xls" && testMsg != "xlsx") {
        this.$message({
          message: "上传文件只能是xls、xlsx格式",
          type: "error",
        });
        return false;
      }
      return true;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.initStudent();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.initStudent();
    },
    handleAvatarSuccess(res) {
      if (res.code == 200) {
        this.$message.success(res.message);
        this.initStudent();
        /*         this.$get("student/detail").then((res) => {
          if (res.code == 200) {
            sessionStorage.setItem("user", JSON.stringify(res));
          }
        }); */
      }
    },
    rowClass() {
      return "text-align: center;";
    },
    headClass() {
      return "text-align: center;background:#f8f8f9;";
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    handleNodeClick(data) {
      this.uid = data.id;
      this.initStudent();
    },
    initStudent() {
      this.$get(
        "student/" +
          this.currentPage +
          "/" +
          this.pageSize +
          "?username=" +
          this.username +
          "&name=" +
          this.name +
          "&mobile=" +
          this.mobile +
          "&email=" +
          this.email +
          "&enabled=" +
          this.enabled +
          "&uid=" +
          this.uid
      ).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data.records;
          this.total = res.data.total;
        }
      });
    },
    initCollege() {
      this.$get("college/").then((res) => {
        if (res.code == 200 && res.data) {
          this.colleges = res.data;
          this.parentData = res.data;
        }
      });
    },
  },
};
</script>

<style>
</style>